<?php

class Rapports extends Table
{
    // Ecrit le tableau des rapports
    public static function Tableau_news($db)//-------------------------------------------------
    {
        $sql="SELECT uti_id, uti_code, uti_nom, uti_prenom, rap_id, rap_date, rap_statut, rap_objet, rap_date as rap_date_brute, DATE_FORMAT(rap_date, '%d/%m/%Y') as rap_date, cli_id, cli_nom".
            ' FROM rapports'.
            ' JOIN clients ON clients.cli_id = rapports.rap_cli_id'.
            ' JOIN utilisateurs ON utilisateurs.uti_id = rapports.rap_uti_id';
        $champs = array ('uti_nom', 'cli_nom', 'rap_date', 'rap_objet');
        $champs_tri = array ('uti_nom', 'cli_nom', 'rap_date_brute', 'rap_objet');
        $msg_vide = LNG_RAP_VIDE;
		return parent::Tableau($db, $sql, $champs, $champs_tri, $msg_vide, True, 2, 0, 0, 10);
    }//------------------------------------------------------------------Tableau
	
	     
    // Ecrit le tableau des rapports
    public static function Tableau_uti($db, $uti_id)//-------------------------------------------------
    {
        $sql="SELECT uti_id, rap_id, rap_date, rap_statut, rap_objet, rap_date as rap_date_brute, DATE_FORMAT(rap_date, '%d/%m/%Y') as rap_date, cli_id, cli_nom".
            ' FROM rapports'.
            ' JOIN clients ON clients.cli_id = rapports.rap_cli_id'.
            ' JOIN utilisateurs ON utilisateurs.uti_id = rapports.rap_uti_id'.
            " WHERE uti_id =$uti_id";
        $champs = array ('cli_nom', 'rap_date', 'rap_objet');
        $champs_tri = array ('cli_nom', 'rap_date_brute', 'rap_objet');
        $msg_vide = LNG_RAP_VIDE;
		return parent::Tableau($db, $sql, $champs, $champs_tri, $msg_vide, True);
    }//------------------------------------------------------------------Tableau


    // Ecrit le tableau des rapports
    public static function Tableau_Cli($db, $cli_id)//-------------------------------------------------
    {
        $sql="SELECT uti_id, uti_nom, uti_prenom, uti_code, rap_id, rap_date as rap_date_brute, DATE_FORMAT(rap_date, '%d/%m/%Y') as rap_date, rap_objet, rap_statut, DATE_FORMAT(rap_date, '%d/%m/%Y') as rap_date, cli_id, cli_nom".
            ' FROM rapports'.
            ' JOIN clients ON clients.cli_id = rapports.rap_cli_id'.
            ' JOIN utilisateurs ON utilisateurs.uti_id = rapports.rap_uti_id'.
            " WHERE cli_id =$cli_id";
        $champs = array ('uti_nom', 'rap_date', 'rap_objet');
        $champs_tri = array ('uti_nom', 'rap_date_brute', 'rap_objet');
        $msg_vide = LNG_RAP_VIDE;
		return parent::Tableau($db, $sql, $champs, $champs_tri, $msg_vide, True);
    }//------------------------------------------------------------------Tableau


    public static function Last_cli($db, $cli_id)
    {
		$sql='SELECT MAX(rap_date) as dernier'.
			' FROM rapports'.
			" WHERE rap_cli_id=$cli_id";
		$result = $db->query($sql);
        $nb = $result->num_rows;
        if (!$nb)
            return -1;
        else
        {
			$row = $result->fetch_assoc();
			return date("Y", strtotime($row['dernier']));
		}
	}
	
	public static function SelectType(){
		return Array( Array('v', 'Visite'), Array('t', 'Téléphonique') );
	}
			
}//*****************************************************************Utilisateurs


class Rapport extends Enregistrement{

	// Constructeur
    //--------------------------------------------------------------------------
    public function __Construct($db){
		// Definition des champs
		$this->defaut = Array(  'rap_id' 	=> -1,
								'rap_type'	=> 'v',
                                'rap_date'  => strftime('%d/%m/%Y'),
                                'rap_date_contact'  => strftime('%d/%m/%Y'),
                                'rap_texte' => '',
                                'rap_cli_id'=> -1,
                                'rap_objet' => '',
                                'rap_uti_id'=> $_SESSION[SES_USER_ID],
                                'rap_statut'=> False,
                                'rap_action'=> Array(),
                                'rap_participant' => Array());				
        parent::__construct($db, 'rapports', 'rap_id');
        $this->externes = Array('rap_participant', 'rap_action');
        $this->dates['rap_date'] = Array('%d/%m/%Y', '%d/%m/%Y');
    }


	public function Ecrire(){
		$retour = parent::Ecrire();
		if ($retour){
			$sql = "UPDATE clients SET cli_annee='".date('Y-m-d')."' WHERE cli_id='{$this->attribut['rap_cli_id']}'";
			$this->db->query($sql);
			switch ($this->onglet){
				case 1:
					$sql = "DELETE FROM participants WHERE par_rap_id='{$this->attribut['rap_id']}'";
					$this->db->query($sql);
					$sql = "INSERT INTO participants (par_rap_id, par_cli_id, par_con_id) VALUES ";
					$sql_par = array();
					foreach	($this->attribut['rap_participant'] as $participant){
						$sql_par[] = "('".$this->attribut['rap_id']."', '".$participant[0]."', '".$participant[1]."')";
					}
					if (count($sql_par)>0){
						$sql .= implode(', ', $sql_par);
					}
					$this->db->query($sql);
					break;
				case 3:
					$sql = "DELETE FROM actions WHERE act_rap_id='{$this->attribut['rap_id']}'";
					$this->db->query($sql);
					$sql = "INSERT INTO actions (act_rap_id, act_uti_id, act_texte, act_date) VALUES ";
					$sql_par = array();
					foreach	($this->attribut['rap_action'] as $action){
						$tab = explode('/',$action[1]);
						$valeur = $tab[2].'-'.$tab[1].'-'.$tab[0].' 00:00:00';
						$sql_par[] = "('".$this->attribut['rap_id']."', '".$action[0]."', '".$action[2]."', '".$valeur."')";
					}
					if (count($sql_par)>0){
						$sql .= implode(', ', $sql_par);
					}
					//echo $sql;
					$this->db->query($sql);
					break;
			}
		}	
		return $retour;
	}


	public function Lire($id){
		$ok = parent::Lire($id);
		if ($ok){
			switch ($this->onglet){
				case 1:
					$this->attribut['rap_participant'] = Array();
					$sql = "SELECT * FROM participants WHERE par_rap_id={$this->Cle()}";
					if ($result = $this->db->query($sql))
					{
						while ($row= $result->fetch_assoc()){
							$this->attribut['rap_participant'][] = Array($row['par_cli_id'],$row['par_con_id']);
						} 
					}					
					break;
				case 3:
					$this->attribut['rap_action'] = Array();
					$sql = "SELECT act_uti_id, act_texte, DATE_FORMAT(act_date, '%d/%m/%Y') as act_date FROM actions WHERE act_rap_id={$this->Cle()}";
					if ($result = $this->db->query($sql))
					{
						while ($row= $result->fetch_assoc()){
							$this->attribut['rap_action'][] = Array($row['act_uti_id'],$row['act_date'], $row['act_texte']);
						} 
					}			
					break;
				//texte
				case 2:
					$texte = $this->attribut['rap_texte'];
					if (strpos($texte,'<p>')==0){
						$texte = str_replace("\n",'</p><p>',$texte);
						$texte = '<p>'.$texte.'</p>';
						$this->attribut['rap_texte']=$texte;
					}
					break;
				default:
					break;
			}
		}
		return $ok;
	}


	public function NomFormat(){
		if ($this->attribut['rap_id'] == -1){

			return 'Nouveau';
		}
		else{
			if ($this->attribut['rap_objet']){
				return $this->attribut['rap_objet'];
			}
			else
			return $this->attribut['rap_id'];
		}
	}



	function Traitement(){
		if ( isset( $_POST['maj_sup'] ) )
		{
			if ( isset( $_POST['confirmation'] ) )
				if ( $this->Supprimer() )
				{
					$_SESSION[SES_STATUT] = LNG_STA_SUP_0;
					header('location:index.php');
				}
				else
					$_SESSION[SES_STATUT] = LNG_STA_ERREUR.LNG_STA_SUP_1;
			else
				$erreur['confirmation'] = LNG_RAP_CONFIRMATION_AIDE;
			return;
		}
		if (isset($_GET['publication'])){
			$this->attribut['rap_statut'] = true;
			$this->Ecrire();
		}
		if (!isset($_POST['maj_infos'])){
			if (isset($_GET['cli_id'])) {
				$this->attribut['rap_cli_id']=$_GET['cli_id'];
			}
		}
		if (isset($_POST['client0'])){
			$this->attribut['rap_participant']=Array();
			for ($i = 0; $i < 20; $i++){
				if (isset($_POST['client'.$i])){
					$this->attribut['rap_participant'][] = array($_POST['client'.$i], $_POST['contact'.$i]);
				}
			}
		}
		if (isset($_POST['utilisateur0'])){
			$this->attribut['rap_action']=Array();
			for ($i = 0; $i < 20; $i++){
				if (isset($_POST['utilisateur'.$i])){
					$this->attribut['rap_action'][] = array($_POST['utilisateur'.$i], $_POST['date'.$i], $_POST['texte'.$i]);
				}
			}
		}
		$part_key = (isset($_GET['part_key']))? $_GET['part_key'] : '';
		if ($part_key){
			$part_tab = split('_', $part_key);
			$this->attribut['rap_participant'] = array();
			$pair = true;
			$j = 0;
			for ($i = 0; $i < count($part_tab)-1; $i++)
			{
				if ($pair){
					if ( $j==$_GET['part_num'] )
						$this->attribut['rap_participant'][] = array($_GET['par_cli_id'],$_GET['par_con_id']);
					else{
						$this->attribut['rap_participant'][] = array($part_tab[$i],$part_tab[$i+1]);
					}
					$j++;
				}
				$pair = !$pair;
			}
		}
		return parent::Traitement();	
	}



	function Verification(){
		switch ($this->onglet)
		{
			case 0:
				$this->erreurs['rap_date'] = "La date n'est pas valide";
				if ( preg_match( '`^\d{1,2}/\d{1,2}/\d{4}$`' , $this->attribut['rap_date']) ){
					$tab_date = split('/', $this->attribut['rap_date']);
					if ( checkdate($tab_date[1], $tab_date[0], $tab_date[2]) ){
						$this->erreurs['rap_date'] = '';
					}
				}
				break;
			case 1:
				$contacts = array();
				$doublons = false;
				$con_vide = false;
				foreach($this->attribut['rap_participant'] as $participant){
					if (!in_array($participant[1], $contacts)){
						$contacts[] = $participant[1];
					}
					else{
						$doublons = true;
						break;
					}
					if (!$participant[1]){
						$con_vide = true;
						break;
					}		
				}
				if ($doublons){
					$this->erreurs['rap_participant'] = 'Il y a des doublons';
					return false;
				}					
				if ($con_vide){
					$this->erreurs['rap_participant'] = 'Un contact est manquant';
					return false;
				}					
				break;
			case 3:
				$this->erreurs['rap_action'] = '';
				foreach	($this->attribut['rap_action'] as $act){
					$moment = $act[1];
					$ok = False;
					if ( preg_match( '`^\d{1,2}/\d{1,2}/\d{4}$`' , $moment) ){
						$tab_date = split('/', $moment);
						if ( checkdate($tab_date[1], $tab_date[0], $tab_date[2]) ){
							$ok = True;
						}
					}
					if (!$ok ){
						$this->erreurs['rap_action'] = "Une date n'est pas valide";
						break;
					}
				}
				break;
			default:
				break;				
		}
	}


	
	function Contenu($erreur,$onglet=0, $edition=False)//-----------------------
	{
		$edition = !$this->attribut['rap_statut'] && $this->attribut['rap_uti_id']==$_SESSION[SES_USER_ID];
		switch ($onglet)
		{
			case 0:// général
?>
<form method='post' action='rapport.php?<?="id={$this->cle()}&edition=$edition"?>'>
<?php
				$this->ChampText('rap_date', False);
				$this->ChampText('rap_objet', $edition);
				$this->ChampSelect('rap_cli_id', $edition);
				$this->ChampSelect('rap_uti_id', False);
				$this->ChampSelect('rap_type', $edition);
				$this->ChampDate('rap_date_contact', $edition);
				if ($edition)
					dohtml_formbouton('labelagauche', 'Mettre à jour', 'maj_infos', 'Annuler');
?>
</form>
<?php
				if ($edition && $this->cle()!=-1)
					echo "Ce rapport est modifiable car non publié. <a href='rapport.php?id={$this->cle()}&publication=1'>Publier ce rapport</a>";				
				if ($this->cle() != -1 && $_SESSION[SES_USER_NIVEAU]>=GR_RAP_SUPPR){
				?>
					<form method='post' action='rapport.php?<?="id={$this->cle()}"?>'>
					<?php	
							dohtml_h4(LNG_H4_SUPPRESSION);
							dohtml_formcheck('labelagauche',
											'confirmation',
											LNG_RAP_CONFIRMATION,
											LNG_RAP_CONFIRMATION_AIDE,
											$erreur['confirmation']);
							dohtml_formbouton('labelagauche', 'Supprimer', 'maj_sup');
					?>
					</form>
				<?php
				}
				break;
				
				
		
		
			case 2://Texte-----------------------------------------------------				
				if (get_magic_quotes_gpc()){
				   $rap_texte = stripslashes( $this->attribut['rap_texte'] );
				}
				else {
					$rap_texte = $this->attribut['rap_texte'];
				}
				if ($edition){
?>
<form method='post' id ='frm_texte' action='rapptexte.php?<?="id={$this->cle()}&edition=$edition"?>'>
	<textarea name='rap_texte' rows='20' style='width:95%'><?=$rap_texte?></textarea>
<?php
	dohtml_formbouton('labelagauche', 'Mettre à jour', 'maj_infos', 'Annuler');
?>
</form>
<?php
				}
				else
					echo nl2br($rap_texte);
				break;
			case 1:// Participants--------------------------------------
?>
<form method='post' action='rappparticipant.php?<?="id={$this->cle()}&amp;edition=$edition"?>'>
<div id='participants'>
<?php
				$num_participant = 0;
				foreach	($this->attribut['rap_participant'] as $part){
					$cli_id = $part[0];
					$con_id = $part[1];
					include('ajax/bloc_participant.php');
					$num_participant++;					
				}
				if ($num_participant==0 && $edition){
					$cli_id = $this->attribut['rap_cli_id'];
					$con_id = '';
					include('ajax/bloc_participant.php');
				}
				if ($edition){
?>
</div>
	<a href='javascript:AjoutParticipant(<?=$cli_id?>);'>Ajouter un participant</a>					
<?php
					if ($this->erreurs['rap_participant']){
						echo '<br/>'.$this->erreurs['rap_participant'];
					}
					dohtml_formbouton('labelagauche', 'Mettre à jour', 'maj_infos', 'Annuler');
				}
?>
</form>
<?php
				break;
			case 3://Actions--------------------------------------------


?>
<form method='post' action='rappaction.php?<?="id={$this->cle()}&amp;edition=$edition"?>'>
<div id='actions'>
<?php
				$num_action = 0;

				foreach	($this->attribut['rap_action'] as $act){
					$uti_id = $act[0];
					$act_date = $act[1];
					$act_texte = $act[2];
					if (get_magic_quotes_gpc()){
					   $act_texte = stripslashes( $act_texte );
					}
					include('ajax/bloc_action.php');
					$num_action++;					
				}
				if ($num_action==0 && $edition){
					$uti_id = $this->attribut['rap_uti_id'];
					$act_date = $this->attribut['rap_date'];
					include('ajax/bloc_action.php');
				}
				if ($edition){
?>
</div>
	<a href='javascript:AjoutAction();'>Ajouter une action</a>					
<?php
					if ($this->erreurs['rap_action']){
						echo '<br/>'.$this->erreurs['rap_action'];
					}
					dohtml_formbouton('labelagauche', 'Mettre à jour', 'maj_infos', 'Annuler');
				}
?>
</form>
<?php
				break;	
		}
	}
	
	function LienPdf(){
		return "<a href='rapsynthese.php?id=".$this->cle()."'><img src='img/print.png'/></a>";
	}	
	
	function Supprimer(){
		$sql = "DELETE FROM participants WHERE par_rap_id='{$this->id}'";
		$this->db->query($sql);
		$sql = "DELETE FROM actions WHERE act_rap_id='{$this->id}'";
		$this->db->query($sql);
		return parent::Supprimer();
	}	
}//*****************************************************************************

?>
